import 'dart:async';

import 'package:bot_toast/bot_toast.dart';
import 'package:cave_flutter/network/whl_api.dart';
import 'package:cave_flutter/routes/whl_app_pages.dart';
import 'package:cave_flutter/utils/whl_toast_utils.dart';
import 'package:cave_flutter/utils/whl_user_utils.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';

class VerifyMobileLogic extends GetxController {
  TextEditingController phoneNumberController = TextEditingController();
  TextEditingController verificationCodeController = TextEditingController();

  Timer? timer;
  int countDown = 60;

  // 当前是否正在倒计时
  bool counting = false;

  // 是否是再次发送
  bool resend = false;

  @override
  void onInit() {
    // TODO: implement onInit
    super.onInit();

    if (WhlUserUtils.getUserInfo().phone?.length == 11) {
      phoneNumberController.text = WhlUserUtils.getUserInfo().phone!.replaceRange(3, 7, "****");
    }
  }

  doClickSendPhoneCode() {
    if (counting) return;

    if (phoneNumberController.text.isEmpty) {
      MyToast.show('请输入手机号');
      return;
    }

    if (phoneNumberController.text.length != 11) {
      MyToast.show('请输入正确的手机号');
      return;
    }

    Map<String, dynamic> params = {
      // "message": "Ut est",
      "phone": [WhlUserUtils.getUserInfo().phone],
      "type": "AUTH_CODE"
    };

    BotToast.showLoading();
    WhlApi.getAuthCode.post(params).then((value) {
      BotToast.closeAllLoading();
      if (value.isSuccess()) {
        counting = true;
        onSendPhoneCode();
      } else {
        MyToast.show(value.msg ?? "获取验证码失败");
      }
    });
  }

  onSendPhoneCode() async {
    if (timer != null) {
      timer!.cancel();
    }
    timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      countDown--;
      if (countDown == 0) {
        timer.cancel();
        countDown = 60;
        counting = false;
        resend = true;
      }
      update();
    });

    // Get.toNamed(Routes.surePhoneCode, arguments: phoneController.text);
  }

  onConfirm() async {
    if (phoneNumberController.text.isEmpty) {
      MyToast.show('请输入手机号');
      return;
    }

    if (phoneNumberController.text.length != 11) {
      MyToast.show('请输入正确的手机号');
      return;
    }

    if (verificationCodeController.text.isEmpty) {
      MyToast.show("请输入验证码");
      return;
    }

    Map<String, dynamic> params = {
      "authCode": verificationCodeController.text,
      "phone": WhlUserUtils.getUserInfo().phone,
    };

    // BotToast.showLoading();
    ResponseData responseData = await WhlApi.forgetPassword.post(params, withLoading: true);
    if (responseData.isSuccess()) {
      Get.toNamed(Routes.setterPasswordPage, arguments: params);
    } else {
      if ((responseData.msg ?? "").isNotEmpty) {
        MyToast.show(responseData.msg!);
      }
    }
    // BotToast.closeAllLoading();
  }
}
